package conf

import (
	"github.com/BurntSushi/toml"
	"github.com/caarlos0/env/v6"
)

var (
	config *Config
)

// 把全局对象保护起来
func C() *Config {
	if config == nil {
		panic("请加载程序配置, LoadConfigFromToml/LoadConfigFromEnv")
	}
	return config
}

func LoadConfigFromToml(path string) (*Config, error) {
	conf := DefaultConfig()
	_, err := toml.DecodeFile(path, conf)
	if err != nil {
		return nil, err
	}

	// 赋值给全局变量
	config = conf
	return conf, nil
}

func LoadConfigFromEnv() (*Config, error) {
	// os.Getenv("MYSQL_DB")
	conf := DefaultConfig()
	err := env.Parse(conf)
	if err != nil {
		return nil, err
	}
	// 赋值给全局变量
	config = conf
	return conf, nil
}
